package com.example.loginregister.presentation;

import com.example.loginregister.business.UserBusinessService;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.example.loginregister.dto.UserRegisterDto;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;

@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();

        try {
            ObjectMapper objectMapper = new ObjectMapper();
            BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
            StringBuilder requestBody = new StringBuilder();
            String line;
            while ((line = reader.readLine())!= null) {
                requestBody.append(line);
            }
            String jsonData = requestBody.toString();
            UserRegisterDto userRegisterDto = objectMapper.readValue(jsonData, UserRegisterDto.class);

            UserBusinessService userBusinessService = new UserBusinessService();
            boolean registerResult = userBusinessService.registerUser(userRegisterDto.getUsername(), userRegisterDto.getPassword(), userRegisterDto.getEmail());

            if (registerResult) {
                out.println("{\"success\": true, \"message\": \"注册成功\"}");
            } else {
                out.println("{\"success\": false, \"message\": \"注册失败，用户名可能已存在，请更换用户名后重试\"}");
            }
        } catch (IOException e) {
            e.printStackTrace();
            out.println("{\"success\": false, \"message\": \"解析请求数据出错，请检查数据格式并重新尝试\"}");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }
}